package com.wzw.springboot.principle.use.security.infrastructure.handle;

import com.wzw.springboot.principle.use.cache.redis.RedisService;
import com.wzw.springboot.principle.use.security.constant.Redis;
import com.wzw.springboot.principle.use.security.infrastructure.model.SecurityUser;
import org.springframework.security.core.userdetails.UserCache;
import org.springframework.security.core.userdetails.UserDetails;

import java.time.Duration;

/**
 * @author Wangzhiwen
 */
public class RedisUserCache implements UserCache {

    private RedisService redisService;

    @Override
    public UserDetails getUserFromCache(String key) {
        return ((SecurityUser) redisService.get(key));
    }

    @Override
    public void putUserInCache(UserDetails user) {
        if (!user.getClass().isAssignableFrom(SecurityUser.class)) {
            return;
        }
        SecurityUser securityUser = (SecurityUser) user;
        redisService.set(Redis.generateTokenKey(securityUser.getId(), securityUser.getUuid()), securityUser, Duration.ofHours(24));
    }

    @Override
    public void removeUserFromCache(String key) {
        redisService.del(key);
    }
}
